const router = require('express').Router();
const mongoose = require('mongoose');
const DictionaryModel = mongoose.models['Dictionary'];
const WorkerModel = mongoose.models['Worker'];

router.get('/get', async function (req, res, next) {
    try{
        let worker=await WorkerModel.findOne({weChatUserId:req.query._id});
        let result={};
        result.worker=worker;
        let dic=await DictionaryModel.findOne({key:'省市区'});
        let workTypeDic=await DictionaryModel.findOne({key:'工种'});
        let expectCitiesDic=await DictionaryModel.findOne({key:'期望工作城市'});
        result.provinces=dic.toVantJson();
        result.workType=JSON.parse(workTypeDic.value);
        result.expectCities=JSON.parse(expectCitiesDic.value);
        res.data(result);
    }catch(e){
        next(e.message);
    }
});

router.post('/save', async function (req, res, next) {
    try{
        let worker=await WorkerModel.findOne({weChatUserId:req.body._id});
        req.body.workType=req.body.workType.split(',');
        req.body.expectCities=req.body.expectCities.split(',');
        req.body.weChatUserId=req.body._id;
        delete req.body._id;
        if(!worker){
            const AutoNumberModel = mongoose.models['AutoNumber'];
            req.body.id=await AutoNumberModel.getNewNumber('Worker');
            await WorkerModel.create(req.body);
        }else{
            Object.assign(worker,req.body);
            await worker.save();
        }
        res.data(true);
    }catch(e){
        next(e.message);
    }
});

module.exports = router;